package com.nitty.cash.loop.ui.activity

import android.graphics.Color
import android.view.View
import com.lib.common.permission.CommonPermissions
import com.lib.common.permission.OnPermissionCallback
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.UiPermissionApplistSmsBinding
import com.nitty.cash.loop.databinding.UiPermissionApplistSmsItemBinding
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.dialog.NittyTipsDialog
import com.nitty.cash.loop.utils.helper.NittyConfigsHelper
import com.nitty.cash.loop.utils.helper.NittyCreditStatusHelper
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import com.nitty.cash.loop.utils.helper.TestDataLibInvoke
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/12/26 10:24
 * @Annotation：Applist、SMS 权限说明页面
 */
class PermissionAppListSmsAct: CommonActivity() {
    lateinit var binding: UiPermissionApplistSmsBinding
    //显示权限类型： 1 Applist  2 SMS
    private var showType = 1
    //是否是审核账号
    var isConfigAccount = false
    override fun getNittyRootView(): View {
        binding = UiPermissionApplistSmsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#FFFAF9F9"))
        setNittyTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setNittyBackBtnRes(R.mipmap.img_back_black)
        setNittyRightBtnRes(R.mipmap.img_customer_black)
        setNittyTextTitleVisibility(View.GONE)
    }

    override fun initNittyListener() {
        //联系客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("AppList And SMS Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"AppList And SMS Page")
        }
        binding.btnTurnOn.setOnClickListener {
            showPermissionAgreeClick()
        }
        binding.btnDisagree.setOnClickListener {
            if (showType == 1){
                showType = 2
                checkShowPermission()
                return@setOnClickListener
            }
            showNittyGetPermissionSuccess(false)
        }
    }

    override fun loadNittyData() {
        isConfigAccount = NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_IS_CONFIG_ACCOUNT)
        showType = 1
        checkShowPermission()
    }

    /**
     * 同意
     */
    private fun showPermissionAgreeClick(){
        val tipsDialog = NittyTipsDialog(this,object : NittyTipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.btnDialogTipsOK -> {
                        requestSmsPermissionAction()
                    }
                    R.id.btnDialogTipsCancel -> {
                    }
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.setTitleText(getString(R.string.dialog_tips))
        if (showType == 2){
            tipsDialog.setTipsText(getString(R.string.permission_agree_tips))
        } else {
            tipsDialog.setTipsText(getString(R.string.permission_read_tips))
        }
    }

    /**
     * 申请权限
     */
    private fun requestSmsPermissionAction(){
        if (showType == 1){
            showType = 2
            checkShowPermission()
            return
        }
        val permissions = NittyConfigsHelper.getNittyPermissionsList()
        CommonPermissions.with(this)
            // 申请多个权限
            .permission(permissions)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        showNittyGetPermissionSuccess(true)
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))

                    if (isConfigAccount){
                        showNittyGetPermissionSuccess(false)
                    } else {
                        CommonPermissions.startPermissionActivity(this@PermissionAppListSmsAct,permissions)
                    }
                }
            })
    }

    /**
     * 权限申请成功
     */
    private fun showNittyGetPermissionSuccess(isAgree: Boolean){
        NittySharedHelper.putNittySharedData(NittySharedKey.NITTY_SHOW_PERMISSION_PAGE,true)
        //同意权限 || 非审核账号
        if (isAgree || !isConfigAccount){
            //上报AppList 和 SMS
            TestDataLibInvoke.sycReadSmsAppListSmsData()
        }

        //进件信息未完成 - 进件信息页面
        if (NittyProcessHelper.getAuthProcessList().size > 0){
            onIntent(ProcessAct::class.java)
            finish()
            return
        }

        val creditStatus = NittyProcessHelper.getAuthBeforeRiskStatus()
        val isCreditRejected = NittyCreditStatusHelper.NittyCreditStatusRepository().isCreditRejected(creditStatus)
        //授信被拒绝 - 拒绝页面
        if (isCreditRejected){
            onIntent(LimitRejectedAct::class.java)
            finish()
            return
        }

        val isCreditReviewing = NittyCreditStatusHelper.NittyCreditStatusRepository().isCreditReviewing()
        //进件信息已完成 && 授信中 - 授信状态查询页面
        if (isCreditReviewing){
            onIntent(LimitReviewingAct::class.java)
            finish()
            return
        }

        //进件信息已完成 && 授信已完成 - 申贷试算页面
        ApplyAct.start(this)
        finish()
    }

    /**
     * 切换显示权限类型
     */
    private fun checkShowPermission(){
        when(showType){
            1 -> {
                showNittyApplistPermissionView()
            }
            else -> {
                showNittySmsPermissionView()
            }
        }
    }

    /**
     * 显示SMS权限信息
     */
    private fun showNittySmsPermissionView(){
        val smsList = arrayListOf<JSONObject>()
        val obj1 = JSONObject()
        obj1.put("title",getString(R.string.permission_sms_why))
        obj1.put("des",getString(R.string.permission_sms_why_desc))
        smsList.add(obj1)

        val obj2 = JSONObject()
        obj2.put("title",getString(R.string.permission_sms_do))
        obj2.put("des",getString(R.string.permission_sms_do_desc))
        smsList.add(obj2)

        val obj3 = JSONObject()
        obj3.put("title",getString(R.string.permission_sms_data_security))
        obj3.put("des",getString(R.string.permission_sms_data_security_desc))
        smsList.add(obj3)

        val obj4 = JSONObject()
        obj4.put("title",getString(R.string.permission_sms_regarding))
        obj4.put("des",getString(R.string.permission_sms_regarding_desc))
        smsList.add(obj4)

        binding.textPermissionTitle.text = getString(R.string.permission_sms_title)
        binding.permissionItemLayout.removeAllViews()
        smsList.forEach {
            val itemBinding = UiPermissionApplistSmsItemBinding.inflate(layoutInflater)
            itemBinding.textTitle.text = it.optString("title")
            itemBinding.textDesc.text = it.optString("des")
            binding.permissionItemLayout.addView(itemBinding.root)
        }
    }

    /**
     * 显示Applist权限信息
     */
    private fun showNittyApplistPermissionView(){
        val smsList = arrayListOf<JSONObject>()
        val obj1 = JSONObject()
        obj1.put("title",getString(R.string.permission_app_list_why))
        obj1.put("des",getString(R.string.permission_app_list_why_desc))
        smsList.add(obj1)

        val obj2 = JSONObject()
        obj2.put("title",getString(R.string.permission_app_list_do))
        obj2.put("des",getString(R.string.permission_app_list_do_desc))
        smsList.add(obj2)

        val obj3 = JSONObject()
        obj3.put("title",getString(R.string.permission_app_list_collect))
        obj3.put("des",getString(R.string.permission_app_list_collect_desc))
        smsList.add(obj3)

        val obj4 = JSONObject()
        obj4.put("title",getString(R.string.permission_app_list_data_safety))
        obj4.put("des",getString(R.string.permission_app_list_data_safety_desc))
        smsList.add(obj4)

        binding.textPermissionTitle.text = getString(R.string.permission_app_list_title)
        binding.permissionItemLayout.removeAllViews()
        smsList.forEach {
            val itemBinding = UiPermissionApplistSmsItemBinding.inflate(layoutInflater)
            itemBinding.textTitle.text = it.optString("title")
            itemBinding.textDesc.text = it.optString("des")
            binding.permissionItemLayout.addView(itemBinding.root)
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_PERMISSION_APPLIST_SMS_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_PERMISSION_APPLIST_SMS_END)
    }
}